<?php

namespace app\common\model;

use think\Model;

class SelfMessage extends Model
{
    // 表名
    protected $name = 'self_message';

    // 开启自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';
    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = NULL;

    // 追加属性
    protected $append = [
        'createtime_text',
        'from_user',
    ];


    public function getTypeList()
    {
        return ['system' => "系统"];
    }

    public function getTypeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['type']) ? $data['type'] : '');
        $list = $this->getTypeList();
        return isset($list[$value]) ? $list[$value] : '';
    }

    public function getCreatetimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['createtime']) ? $data['createtime'] : '');
        
        return $value ? date("Y-m-d H:i", $value) : "";
    }

    public function getFromUserAttr($value, $data)
    {
        $type = isset($data['type']) ? $data['type'] : "system";

        $user_id = isset($data['send_user_id']) ? $data['send_user_id'] : '';

        if($type == "system"){
            $admin = \app\admin\model\Admin::cache(300)->field('id,nickname,avatar')->find($user_id ? 
            $user_id : 1);
            if($admin)
            $admin->avatar = cdnurl($admin->avatar);

            return $admin;
        }

        if($user_id){
            
            
            return \app\common\model\User::cache(300)->field('id,nickname,avatar')->find($user_id);
        }

        return NULL;
        
        return $value ? date("Y-m-d H:i", $value) : "";
    }


    public static function sendSystemMessage($toUserId, $title, $content, $page = '', $admin_id = 0){
        return SelfMessage::create([
            'send_user_id' => $admin_id,
            'to_user_id' => $toUserId,
            'title' => $title,
            'content' => $content,
            'type' => "system",
            'page' => $page,
        ]);
    }
    
}
